<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编码" prop="projectCode">
        <el-input
            v-model="queryParams.projectCode"
            placeholder="请输入项目编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="到期时间" prop="expirationTime">
        <el-date-picker clearable
                        v-model="queryParams.expirationTime"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择到期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
            v-model="queryParams.description"
            placeholder="请输入描述"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:project:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:project:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:project:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:project:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="项目编码" align="center" prop="projectCode" width="100">
        <template #default="scope">


          <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.projectCode"
              placement="top-end"
          >
            <span class="over_text">{{ scope.row.projectCode }}</span>

          </el-tooltip>

        </template>
      </el-table-column>


      <el-table-column label="项目名称" align="center" prop="projectName"/>
      <el-table-column label="到期时间" align="center" prop="expirationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expirationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template #default="scope">
          <el-tooltip
              class="box-item"
              effect="dark"
              content="生成"
              placement="top-end"
          >
            <el-button link type="primary" icon="Download" @click="handleGenerate(scope.row)"
                       v-hasPermi="['system:project:edit']"></el-button>
          </el-tooltip>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="下载"
              placement="top-end"
          >

          </el-tooltip>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="编辑"
              placement="top-end"
          >
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:project:edit']"></el-button>
          </el-tooltip>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="删除"
              placement="top-end"
          >
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:project:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目编码" prop="projectCode">
          <el-input v-model="form.projectCode" placeholder="请输入项目编码"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="密钥" prop="license">
          <el-input v-model="form.license" placeholder="请输入密钥"/>
        </el-form-item>
        <el-form-item label="到期时间" prop="expirationTime">
          <el-date-picker clearable
                          v-model="form.expirationTime"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--    授权码生成-->

    <el-dialog :title="title" v-model="blosopen" width="500px" append-to-body>
      <el-form ref="bioscoRef" :model="bioscoken" :rules="rules" label-width="80px">
        <el-form-item label="结束时间" prop="projectCode">
          <el-space wrap>
            <el-date-picker
                v-model="bioscoken.endTime"
                type="datetime"
                placeholder="选择结束时间"
            />


            <el-button type="warning" @click="editTimelog">永久授权</el-button>
          </el-space>

        </el-form-item>
        <el-form-item label="机器码" prop="projectName">
          <el-input v-model="bioscoken.license" placeholder="请输入机器码"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitblosForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Project">
import {
  addProject,
  delProject,
  getProject,
  listProject,
  posthandleDownload, posthandleGenerate,
  updateProject
} from "@/api/project/index.js";

const {proxy} = getCurrentInstance();

const projectList = ref([]);
const open = ref(false);
const blosopen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectCode: null,
    projectName: null,
    expirationTime: null,
    description: null,
  },
  rules: {}
});
const bioscoken = ref({
  id: null,
  endTime: null,
  license: null
})
const {queryParams, form, rules} = toRefs(data);

// 获取当前日期
const currentDate = new Date();

bioscoken.value.endTime = new Date(currentDate.getTime() + (15 * 24 * 60 * 60 * 1000));


/** 查询项目信息列表 */
function getList() {
  loading.value = true;
  listProject(queryParams.value).then(response => {
    projectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  blosopen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectCode: null,
    projectName: null,
    license: null,
    licensePrivateKey: null,
    licensePublicKey: null,
    expirationTime: null,
    description: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("projectRef");
}

/**
 * 授权码生成
 */
function blosrest() {
  bioscoken.value = ref({
    id: null,
    endTime: null,
    license: null
  })
  proxy.resetForm("bioscoRef");

}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  proxy.resetForm("bioscoRef");

  handleQuery();
}


function editTimelog() {
  // 获取当前日期
  const currentDate = new Date();

  // 将年份增加 200 年
  currentDate.setFullYear(currentDate.getFullYear() + 200);

  // 将结果设置为 endTime
  bioscoken.value.endTime = currentDate;
}


// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加项目信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProject(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目信息";
  });
}

/**
 * 密钥生成
 * @param row
 */

function handleGenerate(row) {

  blosopen.value = true


  bioscoken.value.id = row.id


}

/**
 * 机器码提交获取token
 */
function submitblosForm() {
  proxy.$refs["queryRef"].validate(valid => {
    if (valid) {
      if (bioscoken.value.id != null) {
        const date = new Date(bioscoken.value.endTime);
        bioscoken.value.endTime = date.getTime();

        // 构建下载链接
        const downloadUrl = `${import.meta.env.VITE_APP_BASE_API}system/project/generaLicense/${bioscoken.value.id}/${bioscoken.value.endTime}/${bioscoken.value.license}`;

        window.location.href = downloadUrl;

        blosopen.value = false
        blosrest()


      }
    }
  });
}


//
// /** 提交按钮 */
// function submitForm() {
//   proxy.$refs["projectRef"].validate(valid => {
//     if (valid) {
//       if (form.value.id != null) {
//         updateProject(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         });
//       } else {
//         addProject(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         });
//       }
//     }
//   });
// }


/**
 * 密钥文件下载
 * @param row
 */
function handleDownload(row) {
  posthandleDownload()
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.error(err);
      });
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProject(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除项目信息编号为"' + _ids + '"的数据项？').then(function () {
    return delProject(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/project/export', {
    ...queryParams.value
  }, `project_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style lang="scss" scoped>

.over_text {
  width: 50px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}


</style>
